//
//  RJLoginVC.m
//  AirQuality
//
//  Created by Po on 15/3/10.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJLoginVC.h"
#import "RJLoginChoseView.h"
#import "CommFunc.h"
#import "RJCheckVC.h"
#include <objc/runtime.h>
#import <objc/message.h>


@interface RJLoginVC () <UITextFieldDelegate, RJLoginChoseViewDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *backgroundImage;
@property (weak, nonatomic) IBOutlet UIImageView *inputBoxView;

@property (weak, nonatomic) IBOutlet UITextField *accountTextfiled;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *userStaus;
@property (weak, nonatomic) IBOutlet UIButton *rememberButton;
@property (weak, nonatomic) IBOutlet UIButton *statuasButton;

@property (retain, nonatomic) UITextField * currentTextFiled;
@property (retain, nonatomic) NSMutableDictionary * tempCityData;
@property (retain, nonatomic) NSDictionary * tempPickerData;
@property (assign, nonatomic) BOOL isProvince;                  //省站人员
@property (assign, nonatomic) BOOL isRemember;                  //是否记忆
@property (strong, nonatomic) NSString * cityCode, *cityName;             //存储路径
@property (strong, nonatomic) NSString * vertificationCode;     //验证码



- (void)initData;
- (void)initInterface;
@end

@implementation RJLoginVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    [self registerForKeyboardNotifications];
    objc_msgSend(self, @selector(registerForKeyboardNotifications));
    NSDictionary * dic =[NSDictionary dictionary];
    NSUserDefaults * def =[NSUserDefaults standardUserDefaults];
    dic = [def objectForKey:@"userInfoDic"];
    _tempCityData = [NSMutableDictionary dictionaryWithDictionary:dic];
    _isProvince = [[_tempCityData objectForKey:@"UserRank"] boolValue];
    _isRemember = [[_tempCityData objectForKey:@"RememberBtn"] boolValue];
    _cityName = [_tempCityData objectForKey:@"CityName"];
    _cityCode = [_tempCityData objectForKey:@"CityCode"];
//    [self initInterface];
//    [self checkWifiStatus];
    objc_msgSend(self, @selector(initInterface));
    objc_msgSend(self, @selector(checkWifiStatus));
//    id obj = objc_getClass("RJLoginChoseView");
//   const char *class = object_getClassName(self);
//    unsigned int outCount = 0;
//    objc_property_t * propertys = class_copyPropertyList(obj , &outCount);
//    for (int i = 0; i < outCount; i ++) {
//        objc_property_t property = propertys[i];
//        const char * s = property_getName(property);
////        NSLog(@"%s",class);
//    }
//    [self wokan:@"nihao"];
//    [self methodExchange];
//    [self m2];
    
}

//- (void)wokan:(NSString *)str
//{
//
//}

//- (void)methodExchange
//{
//    Method m1 = class_getInstanceMethod([NSString class], @selector(lowercaseString));
//    Method m2 = class_getInstanceMethod([NSString class], @selector(uppercaseString));
//    method_exchangeImplementations(m1, m2);
//    NSLog(@"%@",[@"sssAAAAss" lowercaseString]);
//}




//+ (void)load
//{
////    Class class = [RJCheckVC class];
////    Method originalSelector = class_getInstanceMethod(self, @selector(viewWillAppear:));
////    Method swizzledSelector = class_getInstanceMethod(class, @selector(viewWillAppear:));
////    BOOL didAddMethod = class_addMethod(self, @selector(viewWillAppear:), method_getImplementation(swizzledSelector), method_getTypeEncoding(swizzledSelector));
////    if (didAddMethod) {
////        class_replaceMethod(self, @selector(viewWillAppear:), method_getImplementation(swizzledSelector), method_getTypeEncoding(swizzledSelector));
////    }else{
////        method_exchangeImplementations(originalSelector, swizzledSelector);
////    }
//    static dispatch_once_t ontToken;
//    dispatch_once(&ontToken, ^{
//        Class class = [RJCheckVC class];
//        SEL originalSelector = @selector(viewWillAppear:);
//        SEL swilledSelector = @selector(viewWillAppear:);
//        Method originalMethod = class_getInstanceMethod(self, originalSelector);
//        Method swilledMethod = class_getInstanceMethod(class, swilledSelector);
//        BOOL didAddMethod = class_addMethod(self, swilledSelector, method_getImplementation(swilledMethod), method_getTypeEncoding(swilledMethod));
//        if (didAddMethod) {
//            class_replaceMethod(self, originalSelector, method_getImplementation(swilledMethod), method_getTypeEncoding(swilledMethod));
//        }else{
//            method_exchangeImplementations(originalMethod, swilledMethod);
//        }
//    });
//}

//+ (void)load
//{
////    id obj = objc_getClass("RJLoginChoseView");
//    Class class = [RJCheckVC class];
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        SEL originalSelector = @selector(wokan:);
//        SEL swizzledSelector = @selector(wokan:);
//        Method originalMethod = class_getInstanceMethod(self, originalSelector);
//        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
//        BOOL didAddMethod =
//        class_addMethod(self,
//                        originalSelector,
//                        method_getImplementation(swizzledMethod),
//                        method_getTypeEncoding(swizzledMethod));
//        if (didAddMethod) {
//            class_replaceMethod(self,
//                                swizzledSelector,
//                                method_getImplementation(swizzledMethod),
//                                method_getTypeEncoding(swizzledMethod));
//        } else {
//            method_exchangeImplementations(originalMethod, swizzledMethod);
//        }
//    
//    });
//}

#pragma mark - Method Swizzling

//- (void)xxx_viewWillAppear:(BOOL)animated {
//    [self xxx_viewWillAppear:animated];
//    NSLog(@"viewWillAppear: %@", self);
//}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_isLogOut) {
        [RJTools showTitle:@"提示" msg:@"注销成功!" cancelString:@"好的" vc:self];
        _isLogOut = NO;
    }
}
#pragma mark - user-defined initialization function
- (void)initData
{

}

- (void)initInterface
{
    NSArray * arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"RJLoginVC" owner:self options:nil];
    self.view = [arrayOfViews objectAtIndex:0];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    [_inputBoxView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"loginBoxBack"]]];
    [_inputBoxView.layer setBorderWidth:1];
    [_inputBoxView.layer setBorderColor:GetRGBColor(180, 211, 241, 1).CGColor];
    [_inputBoxView.layer setCornerRadius:5];
    if (_tempCityData != nil) {
        [_accountTextfiled setText:_tempCityData[@"Account"]];
        [_passwordTextFiled setText:_tempCityData[@"Password"]];
    }
//    [_accountTextfiled setText:_tempCityData[@"Account"]];
    [_accountTextfiled setDelegate:self];
    [_passwordTextFiled setDelegate:self];
//    [_passwordTextFiled setText:_tempCityData[@"Password"]];
    [_passwordTextFiled setSecureTextEntry:YES];
    if (_cityName) {
        [_userStaus setTitle:(_isProvince ? @"省站人员" : _cityName) forState:UIControlStateNormal];
    }else{
     [_userStaus setTitle:(_isProvince ? @"省站人员" : @"市州人员") forState:UIControlStateNormal];
    }
    NSArray *userInfo = [NSArray array];
    if (_tempCityData[@"Account"] == nil) {
        userInfo = nil;
    }else{
       userInfo = @[_tempCityData[@"Account"],_tempCityData[@"Password"]];
    }
    NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
    [userDefailt setObject:userInfo forKey:@"userDefailt"];
    if (!_isRemember) {
       [userDefailt setObject:nil forKey:@"userDefailt"];
          }    
    [_backgroundImage setImage:GetImage(@"loginBackground.png")];
    [self initAllSubViews];
}

- (void)initAllSubViews
{
    if (!_isProvince) {
        [RJUserData defaultRJUserData].currentCity = _tempCityData[@"CityName"];
        [RJUserData defaultRJUserData].currentCityCode = _tempCityData[@"CityCode"];
    }
    
    if (_isRemember) {
        [_rememberButton setSelected:YES];
    }
}

#pragma mark - event
- (IBAction)pressRememberButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    _isRemember = sender.selected;
    if (sender.selected) {
        [RJTools showTitle:@"提醒" msg:@"请确保该当前手机的安全性，否则会造成信息泄露！" cancelString:@"好的" vc:self];
    }else{
        NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
        [def setObject:nil forKey:@"userInfoDic"];
    }
}

- (IBAction)pressLoginButton:(id)sender {
    [self verificationCodeNetWorking];
//    NSUserDefaults * userName = [NSUserDefaults standardUserDefaults];
//    [userName setObject:_accountTextfiled.text forKey:@"userName"];
//    NSString * loginvertificationCode = [_vertificationCode stringByAppendingString:_passwordTextFiled.text];
//    NSMutableDictionary * data = [NSMutableDictionary dictionaryWithDictionary:@{@"username":_accountTextfiled.text,@"password":_passwordTextFiled.text}];
//    [RJUserData defaultRJUserData].isProvince = _isProvince;
//    NSString * loginURL;
//    if (_isProvince) {
//        loginURL = @"http://newair.scemc.cn:5100/smartadmin/login";
//    } else {
//        loginURL = [NSString stringWithFormat:@"http://221.237.179.54:%@/smartadmin/login",_cityCode];
//        [RJUserData defaultRJUserData].currentCityCode = _tempCityData[@"CityCode"];
//    }
//    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:ScreenBounds];
//    [self.view addSubview:loadView];
//    [RJNetWork myNetRequestWithAddress:loginURL data:data completeBlock:^(id responseObject) {
//        if ([[responseObject objectForKey:@"result"] boolValue]) {
//            [self loginInSuccess];
//        } else {
//            [RJTools showTitle:@"登陆失败" msg:@"用户名或密码错误，请重新输入。" cancelString:@"好的" vc:self];
//        }
//        [loadView removeFromSuperview];
//    } failBlack:^(id response) {
//        [RJTools showTitle:@"连接失败" msg:@"登陆失败，请检查网络！" cancelString:@"确定" vc:self];
//        [loadView removeFromSuperview];
//    }];
//    if (_isRemember) {
//        NSDictionary * userInfoDic = @{@"Account":_accountTextfiled.text,
//                                       @"Password":_passwordTextFiled.text,
//                                       @"UserRank":@(_isProvince),
//                                       @"RememberBtn":@(_isRemember),
//                                       @"CityCode":_cityCode ? _cityCode : @"",
//                                       @"CityName":_cityName ? _cityName : @""};
//        NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
//        [def setObject:userInfoDic forKey:@"userInfoDic"];
//        
//    }
//    NSArray *userInfo = [NSArray array];
//    userInfo = @[_accountTextfiled.text,_passwordTextFiled.text];
//    NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
//    [userDefailt setObject:userInfo forKey:@"userDefailt1"];
}
- (void)vertificationSuccess{
    NSUserDefaults * userName = [NSUserDefaults standardUserDefaults];
    [userName setObject:_accountTextfiled.text forKey:@"userName"];
    NSString * loginvertificationCode = [_vertificationCode stringByAppendingString:_passwordTextFiled.text];
    NSMutableDictionary * data = [NSMutableDictionary dictionaryWithDictionary:@{@"username":_accountTextfiled.text,@"password":[CommFunc md5HexDigest:loginvertificationCode]}];
    [RJUserData defaultRJUserData].isProvince = _isProvince;
    NSString * loginURL;
    if (_isProvince) {
        loginURL =[NetURL defaultURL].userLogin;
    } else {
        loginURL = [[NetURL defaultURL] cityUserLogin:_cityCode];
        [RJUserData defaultRJUserData].currentCityCode = _tempCityData[@"CityCode"];
    }
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:ScreenBounds];
    [self.view addSubview:loadView];
    [RJNetWork myNetRequestWithAddress:loginURL data:data completeBlock:^(id responseObject) {
        NSUserDefaults * userId = [NSUserDefaults standardUserDefaults];
        NSString * userId1 = responseObject[@"userId"] ? responseObject[@"userId"]:@"" ;
        NSString * sendCityCode = _cityCode ? _cityCode:@"5100";
        NSArray * userIdArr = @[userId1,sendCityCode];
        [userId setObject:userIdArr forKey:@"userId1"];
        if ([[responseObject objectForKey:@"result"] boolValue]) {
            [self loginInSuccess];
        } else {
            [RJTools showTitle:@"登陆失败" msg:@"用户名或密码错误，请重新输入。" cancelString:@"好的" vc:self];
        }
        [loadView removeFromSuperview];
    } failBlack:^(id response) {
        [RJTools showTitle:@"连接失败" msg:@"登陆失败，请检查网络！" cancelString:@"确定" vc:self];
        [loadView removeFromSuperview];
    }];
    if (_isRemember) {
        NSDictionary * userInfoDic = @{@"Account":_accountTextfiled.text,
                                       @"Password":_passwordTextFiled.text,
                                       @"UserRank":@(_isProvince),
                                       @"RememberBtn":@(_isRemember),
                                       @"CityCode":_cityCode ? _cityCode : @"",
                                       @"CityName":_cityName ? _cityName : @""};
        NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
        [def setObject:userInfoDic forKey:@"userInfoDic"];
        
    }
    NSArray *userInfo = [NSArray array];
    userInfo = @[_accountTextfiled.text,_passwordTextFiled.text];
    NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
    [userDefailt setObject:userInfo forKey:@"userDefailt1"];
}
- (IBAction)pressStatusButton:(UIButton *)sender {
    RJLoginChoseView * choseView = [[RJLoginChoseView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 216, ScreenWidth, 216)];
    [choseView setDelegate:self];
    [self.view addSubview:choseView];
    
}
#pragma mark - function
- (void)loginInSuccess
{
    [[RJUserData defaultRJUserData] setLoginState:YES];
    [[NetURL defaultURL] setUserRank:_isProvince cityCode:_tempCityData[@"CityCode"]];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [self saveUserStatus];
}
- (void)saveUserStatus
{
    //保存用户登录选项
    NSMutableDictionary * userStatus = [NSMutableDictionary dictionary];
    [userStatus setObject:@(_isProvince) forKey:@"UserRank"];
    if (!_isProvince) {
        [userStatus addEntriesFromDictionary:_tempCityData];
        [RJUserData defaultRJUserData].currentCity = _tempCityData[@"CityName"];
        NSUserDefaults *cityName = [NSUserDefaults standardUserDefaults];
        [cityName setObject:_tempCityData[@"CityCode"] forKey:@"cityName1"];
        [RJUserData defaultRJUserData].currentCityCode = _tempCityData[@"CityCode"];
    } else {
        [RJUserData defaultRJUserData].currentCity = @"成都";
        [RJUserData defaultRJUserData].currentCityCode = @"5101";
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"logInEvent" object:nil];
    
    if (_isRemember) {
        [userStatus addEntriesFromDictionary:@{@"Account":_accountTextfiled.text,@"Password":_passwordTextFiled.text}];
    }
    
    [userStatus addEntriesFromDictionary:@{@"RememberBtn":@(_isRemember),@"UserRank":@(_isProvince)}];
    
    if (!_isProvince) {
        [userStatus addEntriesFromDictionary:@{@"CityName":_tempCityData[@"CityName"],@"CityCode":_tempCityData[@"CityCode"]}];
    }
    [userStatus writeToFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:@"UserStatus.plist"] atomically:YES];
}

/**检测网络状态并显示对应提示*/
- (void)checkWifiStatus
{
    NetworkStatus status = [RJTools checkNetStatus];
    if(status == ReachableViaWiFi){
        return;
    } else if (status != NotReachable){
        [RJTools showTitle:@"网络状态不佳" msg:@"您当前处于非Wifi网络，会产生相应的流量费用." cancelString:@"知道了" vc:self];
    } else {
        [RJTools showTitle:@"无网络" msg:@"您当前暂无网络，请连接网络后再试。" cancelString:@"知道了" vc:self];
    }
}

- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShow:)
     
                                                 name:UIKeyboardDidShowNotification object:nil];
}

#pragma mark - system
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - UITextFiledDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _currentTextFiled = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.view.frame.origin.y != 0) {
        [UIView animateWithDuration:0.3 animations:^{
            [self.view setFrame:[UIScreen mainScreen].bounds];
        }];
    }
}

#pragma mark - RJLoginChoseViewDelegate
- (void)LoginChoseView:(RJLoginChoseView *)choseView didEndSelectCityData:(NSDictionary *)data
{
    _cityCode = data[@"CITYCODE"];
    _cityName = data[@"CITYNAME"];
    if (!_cityName) {
        _cityName = @"省站人员";
    }
    _tempPickerData = [NSDictionary dictionaryWithDictionary:data];
    [_tempCityData setObject:data[@"CITYNAME"] forKey:@"CityName"];
    if (![data[@"CITYNAME"] isEqualToString:@"省站人员"]) {
        [_tempCityData setObject:data[@"CITYCODE"] forKey:@"CityCode"];
        _isProvince = NO;
    } else {
        _isProvince = YES;
    }
    
    [_statuasButton setTitle:data[@"CITYNAME"] forState:UIControlStateNormal];
    [choseView freeSelf];
}

#pragma mark - keyboard
- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //kbSize即键盘尺寸 (有width, height)
    CGFloat keyBoardHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//得到键盘的高度
    CGFloat moveHeight = (CGRectGetMaxY(_currentTextFiled.frame) + keyBoardHeight) - ScreenHeight;
    if (moveHeight > 0) {
        CGRect rect = self.view.frame;
        rect.origin.y -= moveHeight;
        [UIView animateWithDuration:0.3f animations:^{
            [self.view setFrame:rect];
        }];
    }
}

# pragma mark -- 验证码
- (void)verificationCodeNetWorking{

    NSString * url = _isProvince ? ([NetURL defaultURL].md3VertificationCode) :[[NetURL defaultURL] cityMd3VertificationCode:_cityCode];
//    NSLog(@"%@",url);
    [RJNetWork myNetRequestWithAddress: url data:@{} completeBlock:^(id responseObject) {
        _vertificationCode = responseObject[@"data"];
        [self vertificationSuccess];
    } failBlack:^(id response) {
    
    }];
  
    
}
@end
